﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Riba.Tools.Controls
{
	public class TextBoxNumeric : TextBox
	{
		public static readonly DependencyProperty IsDecimalProperty =
			DependencyProperty.Register("IsDecimal", typeof(bool), typeof(TextBoxNumeric), null);

		public bool IsDecimal
		{
			get { return (bool)GetValue(IsDecimalProperty); }
			set { SetValue(IsDecimalProperty, value); }
		}

		public TextBoxNumeric()
		{
			TextChanged += TextBoxNumeric_TextChanged;
		}

		void TextBoxNumeric_TextChanged(object sender, TextChangedEventArgs e)
		{
			var be = GetBindingExpression(TextProperty);
			if (be != null)
				be.UpdateSource();
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.OnKeyDown(e);

			if (IsDecimal && e.PlatformKeyCode == 190 && !Text.Contains("."))
			{
				e.Handled = false;
				return;
			}

			if
			(
				(e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key >= Key.D0 && e.Key <= Key.D9 || e.Key == Key.Tab) &&    //so that we can TAB out from the control ;)   
				(Keyboard.Modifiers & ModifierKeys.Shift) == 0 &&
				(Keyboard.Modifiers & ModifierKeys.Control) == 0
			)
			{
				e.Handled = false;
				return;
			}

			// Prevent empty TextBox
			if (string.IsNullOrEmpty(Text))
				Text = "0";

			e.Handled = true;
		}
	}
}
